from threading import Thread
import socket
from socket import socket
from queue import Queue
from time import sleep
import msg_proto
import struct

header_size = 8

class RecvMsgThread(Thread):
    sock:socket = None
    sock_msg_queue:Queue
    pack_buffer:bytes
    uid:int

    def __init__(self, sock, sock_msg_queue):
        super().__init__()
        self.sock = sock
        self.uid = 0
        self.sock_msg_queue = sock_msg_queue
        self.pack_buffer = bytes()

    def set_uid(self, uid):
        self.uid = uid

    def recv_msg(self):
        while True:
            new_recv_data = self.sock.recv(1024)
            if new_recv_data:
                self.pack_buffer += new_recv_data
                while True:
                    if len(self.pack_buffer) < header_size:
                        break
                    else:
                        header_struct = struct.unpack("!2I", self.pack_buffer[:header_size])
                        bin_msg_size = header_struct[0]
                        msg_id = header_struct[1]
                        if len(self.pack_buffer) < header_size + bin_msg_size: # 数据不完整
                            break
                        else:
                            bin_msg = self.pack_buffer[header_size:header_size+bin_msg_size]
                            content = msg_proto.bin_msg_to_content(bin_msg)
                            print(f"[RECV_MSG] USER({self.uid}) msg_id:{msg_id} content:{content}")
                            self.sock_msg_queue.put((msg_id, content))
                            self.pack_buffer = self.pack_buffer[header_size+bin_msg_size:]
            

    def unpack_msg(self, bin_msg):
        return bin_msg.decode('utf-8')

    def run(self):
        running = True
        while(running):
            self.recv_msg()                           
